import execjs
import requests,sys
from copyheaders import headers_raw_to_dict

def spider( word ):

    url = "https://fanyi.baidu.com/v2transapi?from=zh&to=en"

    header = headers_raw_to_dict(
        b'''
        accept: */*
        accept-encoding: gzip, deflate, br
        accept-language: zh-CN,zh;q=0.9
        content-length: 201
        content-type: application/x-www-form-urlencoded; charset=UTF-8
        cookie: BIDUPSID=E84C264EE5C626C9D0C732C7C588BD72; PSTM=1572225664; BAIDUID=E84C264EE5C626C96AC7D0FDBB977388:FG=1; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_PREFER_SWITCH=1; SOUND_SPD_SWITCH=1; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; delPer=0; PSINO=2; pgv_pvi=6702562304; pgv_si=s1379648512; ZP_FR=aladdin-5463-zp_exact_new; BDRCVFR[C0p6oIjvx-c]=I67x6TjHwwYf0; H_PS_PSSID=1432_21099_29567_29700_29220_26350; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1573717698,1573718495,1573719893,1573721418; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1573721505; __yjsv5_shitong=1.0_7_489e3af0f460131e2b08a982d8d1249f742e_300_1573721504173_123.191.227.35_51308233; yjs_js_security_passport=54c8906237f810631ef04f6b1bb9ec2001373abc_1573721505_js; to_lang_often=%5B%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%2C%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%5D; from_lang_often=%5B%7B%22value%22%3A%22pt%22%2C%22text%22%3A%22%u8461%u8404%u7259%u8BED%22%7D%2C%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%2C%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%5D
        origin: https://fanyi.baidu.com
        referer: https://fanyi.baidu.com/translate?aldtype=16047&query=%E5%B1%B1%E7%AB%B9&keyfrom=baidu&smartresult=dict&lang=auto2zh
        sec-fetch-mode: cors
        sec-fetch-site: same-origin
        user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36
        x-requested-with: XMLHttpRequest
        '''
    )

    js = open('./genSign.js',encoding='utf-8',mode='r').read()

    cxt = execjs.compile( js )


    sign = cxt.call("main",word)

    data = {

        "from": "zh",
        "to": "en",
        "query": word,
        "transtype": "translang",
        "simple_means_flag": 3,
        "sign": sign,
        "token": "31e4db0b8629df5e27a8160d3a21bf2c"
    }

    r = requests.post( url = url,headers=header,data=data )

    if r.status_code == 200:

        res = r.json()["trans_result"]["data"][0]["dst"]

        print( '翻译结果:',res )

if __name__ == '__main__':

    word  = sys.argv[1]

    spider(word)